package sapling.security;

import sapling.dao.AdminDao;
import sapling.model.Admin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * Database ShiroRealm
 */
public class DBShiroRealm extends AuthorizingRealm {

    @Autowired
    private AdminDao adminDao;

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Admin admin = adminDao.findOneByUsername(token.getUsername());
        return Objects.isNull(admin) ? null : new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), getName());
    }

    /**
     * 鉴权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) super.getAvailablePrincipal(principalCollection);
        Admin admin = adminDao.findOneByUsername(username);
        if (Objects.nonNull(admin)) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRoles(admin.getRolesName());
            admin.getRoleList().stream().forEach(role -> info.addStringPermissions(role.getPermissionsName()));
            return info;
        }
        return null;
    }
}
